#!/bin/bash

#MYSQL=`which mysql`

rotate=90

_backup() {
  # 如果备份目录不存在则创建它
  if [[ ! -e /backup/mysql.$1 ]]; then
    mkdir -p /backup/mysql.$1
  fi

  # 备份
  sqlFile=/tmp/$1\_`date "+%Y%m%d%H%M%S"`.sql
  mysqldump $1 > $sqlFile

  # 压缩
  dateTime=`date -I`
  backupFile=/backup/mysql.$1/$1-$dateTime.zip
  rm -rf $backupFile

  zip -j -q $backupFile $sqlFile
  rm -rf $sqlFile

  # 清理旧的备份文件
  rotate=$[$rotate+1]
  ls -t /backup/mysql.$1/$1-*|tail -n +$rotate|xargs -r rm -f

  # 输出日志
  dateTime=`date "+%Y-%m-%d %H:%M:%S"`
  echo "$dateTime 备份mysql数据库：$1"
}

# 查询全部数据库名
dbs=`mysql << EOF | tail -n +2
show databases;
EOF`

# 备份自建数据库
for db in $dbs; do
  if [ $db != "mysql" -a $db != "information_schema" -a $db != "performance_schema" -a $db != "sys" ]; then
    _backup $db
  fi
done
